package it.unisa.aDoctor.ui;

import it.unisa.aDoctor.process.RunAndroidSmellDetection;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;

/**
 *
 * @author Dario Di Nucci
 */
public class ResultsUI extends javax.swing.JFrame {
    
    private Class[] TABLE_TYPES = {
        java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class,
        java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class,
        java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class,
        java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
    };

    /**
     * Creates new form SecondStepUI
     *
     * @param inputLocationPath
     */
    public ResultsUI(String inputLocationPath) {
        initComponents();
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (int) ((dimension.getWidth() - this.getWidth()) / 2);
        int y = (int) ((dimension.getHeight() - this.getHeight()) / 2);
        this.setLocation(x, y);
        try {
            this.csvFile = inputLocationPath;
            this.updateTable("");
        } catch (IOException ex) {
            Logger.getLogger(ResultsUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private List<SmellData> filterData(String nameFilter) throws IOException {
        Reader in = new FileReader(this.csvFile);
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);

        List<SmellData> smellDataList = new ArrayList<>();

        for (CSVRecord record : records) {
            String className = record.get("Class");
            List<String> values = new ArrayList<>();
            for (int i = 1; i < record.size(); i++) {
                values.add(record.get(i));
            }

            if (className.contains(nameFilter) || nameFilter.equals("")) {
                SmellData smellData = new SmellData(className, values);
                smellDataList.add(smellData);
            }
        }

        return smellDataList;
    }

    private void updateTable(String nameFilter) throws IOException {
        List<SmellData> filteredDataList = this.filterData(nameFilter);

        DefaultTableModel model = (DefaultTableModel) smellTable.getModel();
        model.setRowCount(0);
        smellTable.setAutoCreateRowSorter(true);

//        TableRowSorter<TableModel> sorter = new TableRowSorter<>(model);
//        smellTable.setRowSorter(sorter);
//        List<RowSorter.SortKey> sortKeys = new ArrayList<>();
//        sortKeys.add(new RowSorter.SortKey(0, SortOrder.DESCENDING));
//        sorter.setSortKeys(sortKeys);
//        sorter.sort();

        for (SmellData filteredData : filteredDataList) {
            Object[] rowData = new Object[filteredData.getValues().size() + 1];
            rowData[0] = filteredData.getClassName();
            for (int i = 0; i < filteredData.getValues().size(); i++) {
                rowData[i + 1] = filteredData.getValues().get(i);
            }
            model.addRow(rowData);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        filterResultsButton = new javax.swing.JButton();
        filterField = new javax.swing.JTextField();
        goBack = new javax.swing.JButton();
        tab1 = new javax.swing.JScrollPane();
        smellTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("PETrA");
        setIconImage(new javax.swing.ImageIcon(getClass().getResource("/aDoctor.png")).getImage());

        filterResultsButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/filter.png"))); // NOI18N
        filterResultsButton.setText("Filter Results");
        filterResultsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                filterResultsButtonActionPerformed(evt);
            }
        });

        filterField.setToolTipText("Filter results.");
        filterField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                filterFieldKeyPressed(evt);
            }
        });

        goBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/back.png"))); // NOI18N
        goBack.setText("Go back");
        goBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                goBackActionPerformed(evt);
            }
        });

        smellTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            RunAndroidSmellDetection.FILE_HEADER
        ) {
            Class[] types = TABLE_TYPES;

            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        smellTable.setColumnSelectionAllowed(true);
        tab1.setViewportView(smellTable);
        smellTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        if (smellTable.getColumnModel().getColumnCount() > 0) {
            smellTable.getColumnModel().getColumn(0).setPreferredWidth(500);
        }

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(tab1, javax.swing.GroupLayout.PREFERRED_SIZE, 719, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                        .addComponent(goBack, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(filterField)
                        .addGap(18, 18, 18)
                        .addComponent(filterResultsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(filterField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(filterResultsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(tab1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(goBack))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void filterResultsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterResultsButtonActionPerformed
        try {
            updateTable(filterField.getText());
        } catch (IOException ex) {
            Logger.getLogger(ResultsUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_filterResultsButtonActionPerformed

    private void goBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goBackActionPerformed
        this.setVisible(false);
        new MainUI().setVisible(true);
    }//GEN-LAST:event_goBackActionPerformed

    private void filterFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_filterFieldKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            try {
                updateTable(filterField.getText());
            } catch (IOException ex) {
                Logger.getLogger(ResultsUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_filterFieldKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField filterField;
    private javax.swing.JButton filterResultsButton;
    private javax.swing.JButton goBack;
    private javax.swing.JTable smellTable;
    private javax.swing.JScrollPane tab1;
    // End of variables declaration//GEN-END:variables
    private String csvFile;
}
